package com.ylz.tedi.myapplication;

import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements
        MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback{
    private RecyclerView recyclerView;
    private BoFangAdpater adpater;
    private TextureView textureView;
    private TextureView textureView1;
    private TextureView textureView2;
    private TextureView textureView3;
    private Surface surface;
    private Surface surface1;
    private Surface surface2;
    private Surface surface3;
    private ArrayList<String> arrayList;
    private ViewPager viewPager;

    private static final String TAG = MainActivity.class.getSimpleName();
    private int mVideoWidth;
    private int mVideoHeight;
    private MediaPlayer mMediaPlayer;
    private SurfaceView mPreview;
    private SurfaceHolder holder;
    private String path;
    private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager=findViewById(R.id.ViewPager);
        mPreview=findViewById(R.id.surface);
        holder = mPreview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        arrayList=new ArrayList<>();
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
//        arrayList.add("rtsp://192.168.1.100/mpeg4cif");
        recyclerView=findViewById(R.id.RecyclerView);
        WrapContentLinearLayoutManagerS s=new WrapContentLinearLayoutManagerS(this);
        s.setOrientation(WrapContentLinearLayoutManagerS.HORIZONTAL);
        recyclerView.setLayoutManager(s);
//        recyclerView.addItemDecoration(new RecycleViewDivider(
//                this, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.colorAccent)));
        adpater=new BoFangAdpater(this,arrayList);
        recyclerView.setAdapter(adpater);
        adpater.notifyDataSetChanged();
        textureView=findViewById(R.id.textureview);
        textureView1=findViewById(R.id.textureview1);
        textureView2=findViewById(R.id.textureview2);
        textureView3=findViewById(R.id.textureview3);
//        textureView.setSurfaceTextureListener(surfaceTextureListener);
//        textureView1.setSurfaceTextureListener(surfaceTextureListener1);
//        textureView2.setSurfaceTextureListener(surfaceTextureListener2);
//        textureView3.setSurfaceTextureListener(surfaceTextureListener3);
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                if (newState == 0) {//当newState == 0时，表示recyclerView已经停止滚动了
//
//
//                }
//            }
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                //当执行完onScrolled方法后，系统会执行onScrollStateChanged方法
//                super.onScrolled(recyclerView, dx, dy);
//                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
//                int lastVisibleItem = ((LinearLayoutManager) manager).
//                        findLastVisibleItemPosition();
//                //visibleItemCount 为RecyclerView 当前可见item的数量
//                int visibleItemCount = manager.getChildCount();
//                int f=lastVisibleItem-visibleItemCount;
//
//
//                Log.d("qwers", "firstVisibleItem" + lastVisibleItem);
//                Log.d("qwers", "可见数量" + visibleItemCount);
//                if (!recyclerView.canScrollHorizontally(-1)) {
//
//                    Log.d("qwer", "到顶了" + dx);
//                } else if (!recyclerView.canScrollHorizontally(1)) {
//
//                    Log.d("qwer", "到底了" + dx);
//                } else if (dx < 0) {
//
//                    Log.d("qwer", "向上划" + dx);
//                } else if (dx > 0) {
//
//                    Log.d("qwer", "向下划" + dx);
//                }
//            }
//        });
    }


    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        Log.d(TAG, "onBufferingUpdate percent:" + percent);

    }

    public void onCompletion(MediaPlayer arg0) {
        Log.d(TAG, "onCompletion called");
    }

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        Log.v(TAG, "onVideoSizeChanged called");
        if (width == 0 || height == 0) {
            Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
            return;
        }
        mIsVideoSizeKnown = true;
        mVideoWidth = width;
        mVideoHeight = height;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG, "onPrepared called");
        mIsVideoReadyToBePlayed = true;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
        Log.d(TAG, "surfaceChanged called");

    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        Log.d(TAG, "surfaceDestroyed called");
    }


    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated called");
        playVideo();

    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaPlayer();
        doCleanUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        doCleanUp();
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
    }

    private void startVideoPlayback() {
        Log.v(TAG, "startVideoPlayback");
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
    }


    private void playVideo() {
        doCleanUp();
        try {

            /*
             * TODO: Set path variable to progressive streamable mp4 or
             * 3gpp format URL. Http protocol should be used.
             * Mediaplayer can only play "progressive streamable
             * contents" which basically means: 1. the movie atom has to
             * precede all the media data atoms. 2. The clip has to be
             * reasonably interleaved.
             *
             */

            path = "http://live.gslb.letv.com/gslb?stream_id=neimenggu&tag=live&ext=m3u8";

            if (path == "") {
                // Tell the user to provide a media file URL.
                Toast
                        .makeText(
                                this,
                                "Please edit MediaPlayerDemo_Video Activity,"
                                        + " and set the path variable to your media file URL.",
                                Toast.LENGTH_LONG).show();
            }

            Log.e("PATH", "Path = " + path);
            // Create a new media player and set the listeners
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setDisplay(holder);
            mMediaPlayer.setOnBufferingUpdateListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnVideoSizeChangedListener(this);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        } catch (Exception e) {
            Log.e(TAG, "error: " + e.getMessage(), e);
        }
    }
    /**
     * 定义TextureView监听类SurfaceTextureListener
     * 重写4个方法
     */
    private TextureView.SurfaceTextureListener surfaceTextureListener=new TextureView.SurfaceTextureListener(){

        private PlayerVideoThread thread;

        /**
         * 初始化好SurfaceTexture后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
            //开启一个线程去播放视频
            thread=new PlayerVideoThread(MainActivity.this,"http://stream.jinhua.com.cn/jykj/app/live.m3u8",surfaceTexture);
            thread.start();
        }

        /**
         * 视频尺寸改变后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

        }

        /**
         * SurfaceTexture即将被销毁时调用
         * @param surfaceTexture
         * @return
         */
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {

//            mMediaPlayer.stop();
//            mMediaPlayer.release();
//            mMediaPlayer=null;
            thread.stops();
            return true;
        }

        /**
         * 通过SurfaceTexture.updateteximage()更新指定的SurfaceTexture时调用
         * @param surfaceTexture
         */
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
            Log.d("dadada","dadadada");
        }
    };

    /**
     * 定义TextureView监听类SurfaceTextureListener
     * 重写4个方法
     */
    private TextureView.SurfaceTextureListener surfaceTextureListener1=new TextureView.SurfaceTextureListener(){

        /**
         * 初始化好SurfaceTexture后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
            //开启一个线程去播放视频
            new PlayerVideoThread(MainActivity.this,"http://stream.jinhua.com.cn/jykj/app/live.m3u8",surfaceTexture).start();
        }

        /**
         * 视频尺寸改变后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

        }

        /**
         * SurfaceTexture即将被销毁时调用
         * @param surfaceTexture
         * @return
         */
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            surface1=null;
//            mMediaPlayer.stop();
//            mMediaPlayer.release();
//            mMediaPlayer=null;
            return true;
        }

        /**
         * 通过SurfaceTexture.updateteximage()更新指定的SurfaceTexture时调用
         * @param surfaceTexture
         */
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

        }
    };
    /**
     * 定义TextureView监听类SurfaceTextureListener
     * 重写4个方法
     */
    private TextureView.SurfaceTextureListener surfaceTextureListener2=new TextureView.SurfaceTextureListener(){

        /**
         * 初始化好SurfaceTexture后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
            //开启一个线程去播放视频
            new PlayerVideoThread(MainActivity.this,"http://stream.jinhua.com.cn/jykj/app/live.m3u8",surfaceTexture).start();
        }

        /**
         * 视频尺寸改变后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

        }

        /**
         * SurfaceTexture即将被销毁时调用
         * @param surfaceTexture
         * @return
         */
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            surface2=null;
            return true;
        }

        /**
         * 通过SurfaceTexture.updateteximage()更新指定的SurfaceTexture时调用
         * @param surfaceTexture
         */
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

        }
    };
    /**
     * 定义TextureView监听类SurfaceTextureListener
     * 重写4个方法
     */
    private TextureView.SurfaceTextureListener surfaceTextureListener3=new TextureView.SurfaceTextureListener(){

        /**
         * 初始化好SurfaceTexture后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
            //开启一个线程去播放视频
            new PlayerVideoThread(MainActivity.this,"http://stream.jinhua.com.cn/jykj/app/live.m3u8",surfaceTexture).start();
        }

        /**
         * 视频尺寸改变后调用
         * @param surfaceTexture
         * @param i
         * @param i1
         */
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

        }

        /**
         * SurfaceTexture即将被销毁时调用
         * @param surfaceTexture
         * @return
         */
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
//            mMediaPlayer.stop();
//            mMediaPlayer.release();
//            mMediaPlayer=null;
            return true;
        }

        /**
         * 通过SurfaceTexture.updateteximage()更新指定的SurfaceTexture时调用
         * @param surfaceTexture
         */
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

        }
    };


}
